import { app, protocol, BrowserWindow, screen } from 'electron';
import path from 'path';
import store from '../store/index';
import { setUser } from './aegis'
import log from 'electron-log'
import eventRouter from "../router/EventRouter"

const PROTOCOL = 'aiassistant';
let pendingProtocolData: any = null;

// 设置协议监听
export function setupProtocolListener() {
  // macOS: 监听 open-url 事件
  app.on('open-url', (event, url) => {
    event.preventDefault();
    if (url.startsWith(`${PROTOCOL}://`)) {
      const data = parseProtocolUrl(url);
      handleProtocolCommand(data);
    }
  });

  // Windows: 处理命令行参数
  if (process.platform === 'win32' && process.argv.length >= 2) {
    const urlArg = process.argv.find(arg => arg.startsWith(`${PROTOCOL}://`));
    if (urlArg) {
      // 首次启动时不处理协议
      // const data = parseProtocolUrl(urlArg);
      // handleProtocolCommand(data);
      pendingProtocolData = parseProtocolUrl(urlArg); // 只存，不执行
    }
  }

  // Windows: 处理第二个实例（当应用已运行时通过协议再次打开）
  app.on('second-instance', (_event, argv) => {
    if (process.platform === 'win32') {
      const urlArg = argv.find(arg => arg.startsWith(`${PROTOCOL}://`));
      if (urlArg) {
        const data = parseProtocolUrl(urlArg);
        handleProtocolCommand(data);
      }
    }
  });
}

app.whenReady().then(() => {
  // 确保 BaseWindow 初始化完成后再处理
  if (pendingProtocolData) {
    handleProtocolCommand(pendingProtocolData);
    pendingProtocolData = null;
  }
});

/**
 * 解析协议URL
 * url 协议URL aiassistant://open-target?type=settings&id=123
 * parsed.hostname 命令 open-target
 * parsed.searchParams 参数 type=settings&id=123
 * Object.fromEntries(parsed.searchParams) === { type: 'settings', id: '123' }
 */
function parseProtocolUrl(url) {
  try {
    // 清理URL（Windows可能会添加引号）
    const cleanUrl = url.replace(/^"|"$/g, '');
    const parsed = new URL(cleanUrl);
    return {
      command: parsed.hostname,
      params: Object.fromEntries(parsed.searchParams)
    };
  } catch (e:any) {
    console.error('协议解析错误:', e);
    return { command: 'error', params: { error: e.message } };
  }
}

// 处理协议命令
function handleProtocolCommand(data) {
  log.info('协议命令', data)
  // 处理命令
  switch (data.command) {
    case 'aiassistant-language':
      if (data.params.language) {
        store.set('language', data.params.language);
      }
      break;
    case 'aiassistant-user-info':
      if (data.params.userInfo) {
        try {
          const decoded = decodeURIComponent(data.params.userInfo)
          const userInfo = JSON.parse(decoded)
          store.set('userInfo', { ...userInfo });
          setUser(userInfo.email)
        } catch (err) {
          log.error('解析 userInfo 失败:', err)
        }
      }
      break;
    case 'aiassistant-open':
      if (data.params.appName) store.set('appName', data.params.appName);
      break;
    case 'aiassistant-show':
      if (data.params.appName) store.set('appName', data.params.appName);
      const tryShow = () => {
        const aiIconWindow = eventRouter?.getApi('aiIconWindow');
        if (aiIconWindow) {
          const { width: screenW, height: screenH } = screen.getPrimaryDisplay().workAreaSize
          let x = screenW - 500
          let y = screenH - 500
          const pos = screen.getCursorScreenPoint();
          if (data.params.posion) {
            if (data.params.posion === 'setAiassistant') {
              x = pos.x + 450
              y = pos.y - 70
            } else if (data.params.posion === 'tryAiassistant') {
              x = pos.x - 100
              y = pos.y - 200
            }
          }
          aiIconWindow.setPosition(x, y)

          // 计算所有屏幕组成的大矩形区域
          const allDisplays = screen.getAllDisplays()
          let screenBounds = allDisplays.reduce((acc, display) => {
            const bounds = display.bounds
            acc.minX = Math.min(acc.minX, bounds.x)
            acc.maxX = Math.max(acc.maxX, bounds.x + bounds.width)
            acc.minY = Math.min(acc.minY, bounds.y)
            acc.maxY = Math.max(acc.maxY, bounds.y + bounds.height)
            return acc
          }, {
            minX: Infinity,
            maxX: -Infinity,
            minY: Infinity,
            maxY: -Infinity,
          })

          // 获取当前鼠标所在屏幕
          const currentDisplay = screen.getDisplayNearestPoint({ x, y })
          const workArea = currentDisplay.workArea

          const mouseRange = { minX: 0, maxX: 0, minY: 0, maxY: 0 } // 所有窗口的范围
          mouseRange.minX = screenBounds.minX
          mouseRange.maxX = screenBounds.maxX
          mouseRange.minY = workArea.y
          mouseRange.maxY = workArea.height + workArea.y
          const bounds = aiIconWindow.frame!.getBounds()
          aiIconWindow.frame?.webContents.send('window-position-updated', { x, y, mouseRange, winW: bounds.width, winH: bounds.height })
          aiIconWindow.show();
        } else {
          setTimeout(tryShow, 500);
        }
      };
      tryShow();
      break;
    case 'aiassistant-hide':
      if (data.params.appName) store.set('appName', data.params.appName);
      // 隐藏ai助手
      BrowserWindow.getAllWindows().forEach(win => {
        if (!win.isDestroyed() && win.isVisible()) {
          win.hide();
        }
      });
      break;
    case 'aiassistant-exit':
      // 退出应用
      app.quit()
      break;
    default:
      console.warn(`未知命令: ${data.command}`);
  }
}


// 设置协议
export function setupProtocol() {
  // 注册协议
  protocol.registerSchemesAsPrivileged([{
    scheme: PROTOCOL,
    privileges: {
      standard: true,
      secure: true,
      supportFetchAPI: true,
      bypassCSP: true
    }
  }]);

  // 设置默认协议客户端
  if (!app.isDefaultProtocolClient(PROTOCOL)) {
    if (process.defaultApp) {
      if (process.argv.length >= 2) {
        app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [path.resolve(process.argv[1])]);
      }
    } else {
      app.setAsDefaultProtocolClient(PROTOCOL);
    }
  }
}
